#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import signal
import pathlib
import asyncio
import asyncio_glib
import strict_hwcfg
from usr_session_common import UsrSessionHelperBase
from usr_session_helper_acli import UsrSessionHelperAdvancedCli
from usr_session_helper_gui import UsrSessionHelperGui
from usr_session_helper_lightbox import UsrSessionHelperLightbox
from usr_session_helper_vnc import UsrSessionHelperVnc


class UsrSession:

    class Access:
        PHYSICAL = "physical"
        SSH = "ssh"
        RDP = "rdp"
        VNC = "vnc"

    class Ui:
        # primary UIs
        ACLI = "acli"
        GUI = "gui"
        VRDESK = "vrdesktop"
        WEBUI = "webui"
        MSWIN_7 = "mswin_7"
        # auxillary UIs
        CLI = "cli"         # pure command line interface for simplest menagement, no sound / peripherals / etc.
        VNC = "vnc"         # pure graphical interface for simplest management, no sound / peripherals / etc.

    class Business:
        WORKSTATION = "workstation"
        ENTERTAINMENT_CENTER = "ecenter"
        PERSONAL_TERMINAL = "pterm"

    @classmethod
    def getAccessDescription(cls, access):
        t = {
            cls.Access.PHYSICAL: "User is in front of a physical seat of this system.",
            cls.Access.SSH: "User interacts with this system using SSH protocol.",
            cls.Access.RDP: "User interacts with this system using RDP protocol.",
            cls.Access.VNC: "User interacts with this system using VNC protocol.",
        }
        return t[access]

    @classmethod
    def getUiDescription(cls, ui):
        t = {
            cls.Ui.ACLI: "Provides user an advanced command line interface, that not only supports command line interaction but also offers features similar to Kitty for displaying images and videos. Additionally, it supports audio I/O, and various peripherals are also functional.",
            cls.Ui.GUI: "Provides user a full fledged graphical user interface.",
            cls.Ui.VRDESK: "Provides user a full fledged VR desktop.",
            cls.Ui.WEBUI: "Provides user a web user interface, with all advanced function such as peripheral redirection and 3D acceleration.",
            cls.Ui.MSWIN_7: "Users operates a Microsoft Windows 7 virtual machine as if it were this system, with all peripherals being managed by the virtual machine.",
            cls.Ui.CLI: "Provides user a basic command line interface.",
            cls.Ui.VNC: "Provides user a minimalist graphical user interface.",
        }
        return t[ui]

    @classmethod
    def getBusinessDescription(cls, business):
        t = {
            cls.Business.WORKSTATION: "As a workstation.",
            cls.Business.ENTERTAINMENT_CENTER: "As an entertainment center.",
            cls.Business.PERSONAL_TERMINAL: "As a personal terminal (such as mobile-phone).",
        }
        return t[business]

    @classmethod
    def getAccessUiBusinessList(cls):
        return cls._combination.keys()

    @classmethod
    def isAccessUiBusinessUsable(cls, access, ui, business):
        assert (access, ui, business) in cls._combination

        try:
            return "session-%s-%s-%s" % (access, ui, business) in pathlib.Path("/var/db/pkg/app-admin/fpemud-os-gentoo-scripts-9999/USE").read_text().split()
        except FileNotFoundError:
            return False

    _combination = {
        (Access.PHYSICAL, Ui.ACLI,     Business.WORKSTATION): UsrSessionHelperAdvancedCli,
        (Access.PHYSICAL, Ui.GUI,      Business.WORKSTATION): UsrSessionHelperGui,
        # (Access.PHYSICAL, Ui.MSWIN_7, Business.WORKSTATION): UsrSessionHelperLightbox,
        (Access.VNC,  Ui.VNC,      Business.WORKSTATION): UsrSessionHelperVnc,
    }

    def __init__(self, id, access, ui, business, **kwargs):
        if not self.isAccessUiBusinessUsable(access, ui, business):
            raise Exception("session \"%s-%s-%s\" is not usable" % (access, ui, business))

        self._id = id
        self._access = access
        self._ui = ui
        self._business = business

        self._helper = self._combination[(access, ui, business)](self, self._id, **kwargs)
        assert isinstance(self._helper, UsrSessionHelperBase)

        self._mainloop = None

    def run(self):
        asyncio.set_event_loop_policy(asyncio_glib.GLibEventLoopPolicy())
        self._mainloop = asyncio.get_event_loop()

        machine = strict_hwcfg.probe()

        self._helper.start(machine)
        try:
            self._mainloop.add_signal_handler(signal.SIGINT, self._sigHandlerINT)
            self._mainloop.add_signal_handler(signal.SIGTERM, self._sigHandlerTERM)
            self._mainloop.run_forever()
        finally:
            self._helper.exit()

    def _sigHandlerINT(self):
        self._mainloop.stop()
        return True

    def _sigHandlerTERM(self):
        self._mainloop.stop()
        return True


class UsrSessionConfig:
    pass
    # Idle
    # guint input_mask;
    # guint idle_sec;
    # Lock */
    # gboolean on_idle;
    # gboolean on_sleep;
    # Backlights */
    # GHashTable *backlights;
    # Hooks */
    # GPtrArray *hooks;
    # DPMS */
    # gboolean dpms_enable;
    # guint standby_sec;
    # guint suspend_sec;
    # guint off_sec;
    # guint lock_standby_sec;
    # guint lock_suspend_sec;
    # guint lock_off_sec;
    # WIREPLUMBER
    # gboolean mute_audio;


# It allows you to set various settings, such as
# the default font, cursor blinking and mouse behaviour

# set env
# $BROWSER

# no plugin
# $XDG_CONFIG_DIRS/rox.sourceforge.net/ROX-Session/Environment.py       no plugin
# $XDG_CONFIG_DIRS/rox.sourceforge.net/ROX-Session/Styles               no plugin

# make it simpler
# If the window mananger crashes, or you quit it, ROX-Session will ask you to
# choose another one. The chosen window manager the default for future sessions.
# Errors

# remove
# Running ROX-Filer
# Message display

# do
# run autostart.desktops
